/**
 * Created by zhaojm on 15/3/17.
 */
game.CoinLayer = cc.Layer.extend({



    _coinList : null,
    ctor:function(){
        this._super();
        this._coinList = [];

        var size = cc.winSize;


        var numlist = [0,1,2,3,3];
        for(var i = 0; i < numlist.length; i++){
            var coin = this.addOneCoin(game.ConfigHelper.getOneCoinMatrixByIndex(numlist[i]));
            //if(coin.getPositionX() > size.width){
            //    break;
            //}
        }




        this.scheduleUpdate();

    },

    update:function(dt){
        this._super();
        // TODO 删除 和 创建 Coin
        if(this._coinList[this._coinList.length - 1].getPositionX() + this.parent.getPositionX() < cc.winSize.width + 10){
            this.addOneCoin();
        }
        while(true){

            if(this._coinList[0].getPositionX() + this._coinList[0].getContentSize().width <= -this.parent.getPositionX()){
                //cc.log('removeCoin');
                this.removeChild(this._coinList[0]);

                this._coinList.splice(0, 1);

            }else{
                break;
            }
        }

        // TODO 获取 hero 的 rect，然后， 遍历 _coinList,检测碰撞


        var rectHero = cc.rect(
            this.parent.hero.getPositionX(),
            this.parent.hero.getPositionY(),
            this.parent.hero.getContentSize().width,
            this.parent.hero.getContentSize().height
        );

        for (var i = 0; i < this._coinList.length; i++) {
            this._coinList[i].checkCollided(rectHero);
        }





    },

    addOneCoin:function(m){
        //cc.log('addOneCoin');
        //var numlist = [
        //    1, 1, 0, 1, 1,
        //    1, 1, 1, 1, 1,
        //    1, 1, 1, 1, 1,
        //    1, 0, 0, 0, 1
        //];
        //var x = 5;
        //var y = 4;
        //
        //
        //var matrix = game.Matrix.makeMatrix(x, y, numlist);
        if(!m) {
            var matrix = game.ConfigHelper.getOneCoinMatrix();
        }else{
            var matrix = m;
        }

        var coin = new game.Coin(matrix);

        if(this._coinList.length == 0){
            coin.setPosition(cc.p(400, cc.winSize.height / 2 ));
        }else{
            var lastCoin = this._coinList[this._coinList.length - 1];

            if(m){
                var w = lastCoin.getPositionX() + lastCoin.getContentSize().width + 30;
            }else{
                var w = lastCoin.getPositionX() + lastCoin.getContentSize().width + game.ConfigHelper.getCoinInterval();
            }

            coin.setPosition(cc.p(w,
                //lastCoin.getPositionX() + lastCoin.getContentSize().width + game.ConfigHelper.getCoinInterval(),
                cc.winSize.height * game.ConfigHelper.getCoinYPercent()
            ));
        }

        this.addChild(coin);
        this._coinList.push(coin);

        return coin;
    },







});